package net.sudot.chess.plugin.login.wechat;


import net.sudot.chess.business.model.PluginConfig;
import net.sudot.chess.plugin.PluginAttributeConfig;
import net.sudot.chess.plugin.login.LoginPlugin;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 微信登录插件
 *
 * @author tangjialin on 2018-03-18.
 */
@Component
public class WechatLoginPlugin extends LoginPlugin {

    /**
     * code请求URL
     */
    private static final String CODE_REQUEST_URL = "https://open.weixin.qq.com/connect/oauth2/authorize#wechat_redirect";

    /**
     * openId请求URL
     */
    private static final String OPEN_ID_REQUEST_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";

    @Override
    public String getName() {
        return "微信登录";
    }

    @Override
    public List<PluginAttributeConfig> getAttributeConfigs() {
        return null;
    }

    @Override
    public boolean supports(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT");
        return StringUtils.contains(userAgent.toLowerCase(), "micromessenger");
    }

    @Override
    public void loginHandle(String extra, HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) {
        Map<String, Object> parameterMap = new TreeMap<>();
        parameterMap.put("appid", getAppId());
        parameterMap.put("redirect_uri", getLoginAfterUrl(extra));
        parameterMap.put("response_type", "code");
        parameterMap.put("scope", "snsapi_userinfo");

        modelAndView.addObject("requestUrl", CODE_REQUEST_URL);
        modelAndView.addObject("parameterMap", parameterMap);
        modelAndView.setViewName(LoginPlugin.DEFAULT_LOGIN_VIEW);

    }

    @Override
    public boolean isLoginSuccess(String extra, HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        if (StringUtils.isEmpty(code)) {
            return false;
        }
//        try {
//            OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
//            TokenRequestBuilder tokenRequestBuilder = OAuthClientRequest.tokenLocation(OPEN_ID_REQUEST_URL);
//            tokenRequestBuilder.setParameter("appid", getAppId());
//            tokenRequestBuilder.setParameter("secret", getAppSecret());
//            tokenRequestBuilder.setCode(code);
//            tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
//            OAuthClientRequest accessTokenRequest = tokenRequestBuilder.buildQueryMessage();
//            OAuthJSONAccessTokenResponse authJSONAccessTokenResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.GET);
//            String openId = authJSONAccessTokenResponse.getParam("openid");
//            String accessToken = authJSONAccessTokenResponse.getParam("access_token");
//            if (StringUtils.isNotEmpty(openId) && StringUtils.isNotEmpty(accessToken)) {
//                request.setAttribute("openid", openId);
//                request.setAttribute("access_token", accessToken);
//                return true;
//            }
//        } catch (OAuthSystemException e) {
//            throw new BusinessException(e.getMessage(), e);
//        } catch (OAuthProblemException e) {
//            throw new BusinessException(e.getMessage(), e);
//        }
        return false;
    }

    @Override
    public String getUniqueId(HttpServletRequest request) {
        String openId = (String) request.getAttribute("openid");
        return StringUtils.isNotEmpty(openId) ? openId : null;
    }

    /**
     * 获取AppID
     *
     * @return AppID
     */
    private String getAppId() {
        PluginConfig pluginConfig = getConfig();
        return pluginConfig.getAttribute("appId");
    }

    /**
     * 获取AppSecret
     *
     * @return AppSecret
     */
    private String getAppSecret() {
        PluginConfig pluginConfig = getConfig();
        return pluginConfig.getAttribute("appSecret");
    }

}